package com.otp.webapp.action;

import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.appfuse.model.User;

import com.otp.model.test.instance.TestInstance;
import com.otp.service.instance.TestInstanceManager;


public class TestInstanceList extends BasePage implements Serializable {
	
	private static final long serialVersionUID = -6143415000723353764L;
 
	private TestInstanceManager testInstanceManager;
	private String userId;
	private List<TestInstance> testInstances;
	private int ready;
	private int completed;
	private int maySeeResults;
	private boolean testInstancesFetched=false;

    public TestInstanceList() {
        setSortColumn("objectId");
        testInstancesFetched=false;
    }
	
	 public void setTestInstanceManager(TestInstanceManager testInstancesManager) {
      this.testInstanceManager = testInstancesManager;
     }
	 
	public String getUserId() {
		if(userId==null){
			HttpServletRequest request = getRequest();
			User user = userManager.getUserByUsername(request.getRemoteUser());
			this.userId=user.getId().toString();
		}
		return this.userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public int getReady(){
		if(!testInstancesFetched) fetchTestInstances();
		return ready;
	}

	public int getCompleted(){
		if(!testInstancesFetched) fetchTestInstances();
		return completed;
	}
	
	public int getMaySeeResults(){
		if(!testInstancesFetched) fetchTestInstances();
		return maySeeResults;
	}
	
	public List<TestInstance> getTestInstances(){
		if(!testInstancesFetched) fetchTestInstances();
		return testInstances;
	}
	

    public List<TestInstance> fetchTestInstances() {
    	
    	@SuppressWarnings("unchecked")
		List<TestInstance> testInstancesSorted = sort(testInstanceManager.getTestInstanceByUser(getUserId(),null));
        testInstances = testInstancesSorted;
                
        ready = 0;
        completed = 0;
        maySeeResults = 0;
        for(TestInstance test:testInstances){
        	String state = test.getTestInstanceState().getState();
        	if(state.equals("READY")) ready++;
        	if(state.equals("COMPLETED")) {
        		completed++;
        		if(test.isShowResult()) maySeeResults++;
        	}
        }
        testInstancesFetched=true;
        return testInstances;
    }
    
}
